package com.gillion.tms.service.impl;

import com.gfa4j.security.domain.SysResource;
import com.gfa4j.security.domain.SysResourceRelation;
import com.gfa4j.security.function.service.ResourceService;
import com.gfa4j.utils.ResourceUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.web.util.AntPathRequestMatcher;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.util.List;
import java.util.Map;

/**
 * User: liaowj
 * Date: 2015/4/12
 * Time: 20:04
 */
@Service("resourceService")
public class ResourceServiceImpl implements ResourceService, InitializingBean {

    @Autowired
    private DataSource dataSource;
    private JdbcTemplate jdbcTemplate;

    @Override
    public Map<AntPathRequestMatcher, SysResource> loadAllUrlMatcherWithResource() {
        final List<SysResource> resources = jdbcTemplate.query("SELECT RESOURCE_ID, URL  FROM sys_resource", BeanPropertyRowMapper.newInstance(SysResource.class));
        final List<SysResourceRelation> resourceRelations = jdbcTemplate.query("SELECT RESOURCE_ID, RESOURCE_REL_ID FROM SYS_RESOURCE_REL", BeanPropertyRowMapper.newInstance(SysResourceRelation.class));
        return ResourceUtils.buildResourceData(resources, resourceRelations);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

}
